﻿
var InvoiceApplyId = "";
var flag = 0;
if (typeof ($) != "undefined") {
    $(document).ready(function () {
        flag = getPar1("flag");
        //debugger
        parent.setAddNewButtonHiden();

        if (flag != 0) {
            LoadInvoiceApplyDataByWorkFlowInsId(WorkflowInsId);
        }

        if (flag == 1) {  //下一流程节点
            document.getElementById("InvoiceDiv").style.display = "block";
            document.getElementById("ExperssDiv").style.display = "block";
            $("#btnOrderID").hide();
            AddTrRow();
        } else if (flag == 2) {  //查看
            document.getElementById("InvoiceDiv").style.display = "block";
            document.getElementById("ExperssDiv").style.display = "block";
            $("#btnOrderID").hide();
            $("#btnAdd").hide();
            $("#btnDel").hide();
            var invoiceApplyId = getPar1("id");
            GetApplyProductByApplyId(invoiceApplyId);
        } else if (flag == 3) { //修改
            document.getElementById("InvoiceDiv").style.display = "block";
            document.getElementById("ExperssDiv").style.display = "block";
            var invoiceApplyId = getPar1("id");
            GetApplyProductByApplyId(invoiceApplyId);
        }
    });
}

var OrderProductId;
var ValueChanged = function (rowobj) {
    OrderProductId = $("#OrderProductId").val();
    var vOrderId = $("#OrderID").val();
    GetCustomerDataByOrderId(vOrderId);
    GetProductDataByOrderId(vOrderId);
}
var TextChanged = function (rowobj) {
    var ProductName = $("#txtOrderProductId").val();
    if (OrderProductId == "" || OrderProductId == "undefined") {
        return;
    }
    if (ProductName == "" || ProductName == "undefined") {
        return;
    }
    $("#OrderProductId", rowobj).val(OrderProductId);
    $("#txtOrderProductId", rowobj).val(ProductName);
    GetInvoiceCode(rowobj);
}

var LoadInvoiceApplyDataByWorkFlowInsId = function (WorkFlowInsId) {
    var url = "";
    if (flag == 3 || flag == 2) {
        var vId = getPar1("id");
        url = "../Extend/AjaxData/JsonList.aspx?r=" + Math.random() + "&entity=CrmInvoiceApply&condition=ID='" + vId + "'";
    } else {
        url = "../Extend/AjaxData/JsonList.aspx?r=" + Math.random() + "&entity=CrmInvoiceApply&condition=WorkFlowInsId='" + WorkFlowInsId + "'";
    }
    $.get(url, function (d, s) {
        var list = eval("(" + d + ")");
        for (var i = 0; i < list.rows.length; i++) {
            //var orderId = instance[0].OrderId;

            var vType = list.rows[i].InvoiceApplyType;
            var selectType = document.getElementById("InvoiceApplyType");
            for (var j = 0; j < selectType.options.length; j++) {
                if (selectType.options[j].value == vType) {
                    $("#InvoiceApplyType").get(0).selectedIndex = j;
                }
            }
            var vApplyType = list.rows[i].ApplyType;
            var selectApplyType = document.getElementById("ApplyType");
            for (var k = 0; k < selectApplyType.options.length; k++) {
                if (selectApplyType.options[k].value == vApplyType) {
                    $("#ApplyType").get(0).selectedIndex = k;
                }
            }
            var vCostMethod = list.rows[i].CostMethod;
            var selectCostMethod = document.getElementById("CostMethod");
            for (var m = 0; m < selectCostMethod.options.length; m++) {
                if (selectCostMethod.options[m].value == vCostMethod) {
                    $("#CostMethod").get(0).selectedIndex = m;
                }
            }
            var vInvoiceType = list.rows[i].InvoiceType;
            var selectInvoiceType = document.getElementById("InvoiceType");
            for (var n = 0; n < selectInvoiceType.options.length; n++) {
                if (selectInvoiceType.options[n].value == vInvoiceType) {
                    $("#InvoiceType").get(0).selectedIndex = n;
                }
            }
            $("#Identifier").val(list.rows[i].Identifier);
            $("#BillingMoney").val(list.rows[i].BillingMoney);
            $("#CostUser").val(list.rows[i].CostUser);
            $("#ApplyBank").val(list.rows[i].ApplyBank);
            $("#ApplyAccount").val(list.rows[i].ApplyAccount);
            $("#Addressee").val(list.rows[i].Addressee);
            $("#Contact").val(list.rows[i].Contact);
            $("#MailingAddress").val(list.rows[i].MailingAddress);

            InvoiceApplyId = list.rows[i].ID;
            var orderId = list.rows[i].OrderId;
            GetCustomerDataByOrderId(orderId);
            GetProductDataByOrderId(orderId);
        }
    });
}

//获取客户信息
var GetCustomerDataByOrderId = function (orderId) {
    //debugger
    var url = "../Extend/AjaxData/JsonList.aspx?r=" + Math.random() + "&entity=V_CrmCustomerInfoOrderProduct&condition=ID='" + orderId + "'";
    $.get(url, function (d, s) {
        var list = eval("(" + d + ")");
        for (var i = 0; i < list.rows.length; i++) {
            if (flag == 1 || flag == 2 || flag == 3) {
                $("#OrderID").val(list.rows[i].ID);
                $("#txtOrderID").val(list.rows[i].Code);
            }
            var CustomerName = list.rows[i].CustomerName;
            var CustomerType = list.rows[i].CustomerTypeName;
            var CustomerSource = list.rows[i].CustomerOriginName;
            var CustomerTrade = list.rows[i].CustomerTradeName;
            var AddUserName = list.rows[i].MessageName;
            var SealiverName = list.rows[i].SaleadviserName;
            var TechName = list.rows[i].LectorUserName;
            var CustomerMgrName = list.rows[i].CustomeerMgrName;
            if (typeof (CustomerName) != "undefined") {
                $("#CustomerName").val(CustomerName);
                $("#CustomerType").val(CustomerType);
                $("#CustomerSource").val(CustomerSource);
                $("#CustomerTrade").val(CustomerTrade);
                $("#AddUserName").val(AddUserName);
                $("#SealiverName").val(SealiverName);
                $("#TechName").val(TechName);
                $("#CustomerMgrName").val(CustomerMgrName);
            }
        }
    });
}
//获取产品信息
var GetProductDataByOrderId = function (orderId) {
    //debugger
    var url = "../Extend/AjaxData/JsonList.aspx?r=" + Math.random() + "&entity=V_CrmCustomerInfoOrderProduct&condition=ID='" + orderId + "'";
    $.get(url, function (d, s) {
        $("#DetailDiv tbody").html("");
        var list = eval("(" + d + ")");
        for (var i = 0; i < list.rows.length; i++) {
            $("#DetailDiv tbody").append("<tr>" +
                "<td style='text-align: center'>" + list.rows[i].ProductName + "</td>" +
                "<td style='text-align: center'>" + list.rows[i].ProductTypeName + "</td>" +
                "<td style='text-align: center'>" + list.rows[i].Amount + "</td>" +
                "<td style='text-align: center'>" + list.rows[i].AccountReceivable + "</td>" +
                "<td style='text-align: center'>" + list.rows[i].ProductResignMoney + "</td>" +
                "<td style='text-align: center'>" + list.rows[i].DeliverPersonCount + "</td>" +
                "<td style='text-align: center'>" + list.rows[i].InvoiceMoney + "</td>" +
                    "</tr>");
        }
    });
}
//获取产品发票申请
var GetApplyProductByApplyId = function (invoiceApplyId) {
    var url = "../Extend/AjaxData/JsonList.aspx?r=" + Math.random() + "&entity=V_CrmInvoiceAppProduct&condition=InvoiceApplyId='" + invoiceApplyId + "'";
    $.get(url, function (d, s) {
        //debugger
        var list = eval("(" + d + ")");
        for (var i = 0; i < list.rows.length; i++) {
            $("#InvoiceDiv tbody").append("<tr>" +
                "<td>" +
                "<input id='CrmInvoiceApplyProductId' name='CrmInvoiceApplyProductId' type='hidden' value='" + list.rows[i].ID + "' /> " +
                "<input id='OrderProductId' name='OrderProductId' type='hidden' value='" + list.rows[i].OrderProductId + "' />" +
                "<input id='txtOrderProductId' name='txtOrderProductId' value='" + list.rows[i].ProductName + "' readonly='readonly' style='border-bottom-style: none; border-bottom-color: transparent; border-right-style: none; border-top-color: transparent; width: 250px; border-top-style: none; border-right-color: transparent; border-left-style: none; border-left-color: transparent' type='text' />" +
                "</td>" +
                "<td>" +
                "<input id='InvoiceCodeId' name='InvoiceCodeId' type='hidden' value='" + list.rows[i].InvoiceCodeId + "' />" +
                "<input id='InvoiceCodeId' name='InvoiceCode' readonly='readonly' value='" + list.rows[i].InvoiceCode + "' style='border-bottom-style: none; border-bottom-color: transparent; border-right-style: none; border-top-color: transparent; width: 150px; border-top-style: none; border-right-color: transparent; border-left-style: none; border-left-color: transparent' type='text' />" +
                "</td>" +
                "<td>" +
                "<input id='InvoiceNumber' name='InvoiceNumber' readonly='readonly' value='" + list.rows[i].InvoiceNumber + "' style='border-bottom-style: none; border-bottom-color: transparent; border-right-style: none; border-top-color: transparent; width: 150px; border-top-style: none; border-right-color: transparent; border-left-style: none; border-left-color: transparent' type='text' />" +
                "</td>" +
                "<td style='width: 150px'>" +
                "<input id='InvoiceMoney' name='InvoiceMoney' value='" + list.rows[i].InvoiceMoney + "' style='border-bottom-style: none; border-bottom-color: transparent; border-right-style: none; border-top-color: transparent; width: 150px; border-top-style: none; border-right-color: transparent; border-left-style: none; border-left-color: transparent' type='text' />" +
                "</td>" +
            "</tr>");
        }
        if (flag == 3) {
            AddTrRow();
        }
    });
}

//获取发票代码和发票号码
var iCount = -1, ids = "", idInvoiceCodeId = "", idCode = "", idNumber = "", idMoney = "",
    iConditionNumber = [], tempData = "";
var GetInvoiceCode = function (rowobj) {
    var tempCondition = "";
    if (iCount == 0) {
        tempCondition = "1=1";
    } else {
        var tempCode = "", tempNumber = "";
        for (var j = 0; j < iConditionNumber.length; j++) {
            tempNumber += ",'" + iConditionNumber[j] + "'";
        }
        tempCode = tempCode.substring(1, tempCode.length);
        tempNumber = tempNumber.substring(1, tempNumber.length);
        tempCondition = "InvoiceNumber not in(" + tempNumber + ")";
    }
    var conditioin = "InvoiceType='16754374-F608-4520-A28A-67E65207FBA0' and " +
                        " InvoiceState='EB944471-8371-4BD7-9358-03C24F1F1AF3' " +
                        " and " + tempCondition + " order by InvoiceCode,InvoiceNumber";
    var url = "../Extend/AjaxData/JsonList.aspx?r=" + Math.random() + "&entity=CrmInvoiceCode&condition=" + encodeURI(conditioin) + "";
    $.get(url, function (d, s) {
        var list = eval("(" + d + ")");
        tempData = "";
        for (var i = 0; i < list.rows.length; i++) {
            if (flag == 1 || flag == 3) {
                $("#InvoiceCodeId", rowobj).val(list.rows[0].ID);
                $("#InvoiceCode", rowobj).val(list.rows[0].InvoiceCode);
                $("#InvoiceNumber", rowobj).val(list.rows[0].InvoiceNumber);
                if (tempData != list.rows[0].InvoiceCode) {
                    iConditionNumber.push(list.rows[0].InvoiceNumber);
                }
                tempData = list.rows[0].InvoiceCode;
            }
        }
    });
    var tr = $("#tbInvoice tr").eq(1);
    $("#OrderProductId", tr).val("");
    $("#txtOrderProductId", tr).val("");
}

//保存数据
var Save = function () {
    //debugger
    setValue();
    if (instance[0].InvoiceApplyType == "") {
        alert("申请类型不能为空!");
        $("#InvoiceApplyType").focus();
        return;
    }
    if (instance[0].OrderID == "") {
        alert("订单号不能为空!请选择!");
        $("#txtOrderID").focus();
        return;
    }
    if (instance[0].ApplyType == "") {
        alert("开发票类型不能为空!");
        $("#ApplyType").focus();
        return;
    }
    if (instance[0].InvoiceType == "") {
        alert("发票类型不能为空!");
        $("#InvoiceType").focus();
        return;
    }
    if (instance[0].Identifier == "") {
        alert("纳税人识别号不能为空!");
        $("#Identifier").focus();
        return;
    }
    if (instance[0].BillingMoney == "") {
        alert("开票金额不能为空!");
        $("#BillingMoney").focus();
        return;
    } else {
        if (instance[0].BillingMoney == "0") {
            alert("开票金额不能为0!");
            $("#BillingMoney").focus();
            return;
        }
    }
    if (instance[0].ApplyBank == "") {
        alert("开户银行不能为空!");
        $("#ApplyBank").focus();
        return;
    }
    if (instance[0].ApplyAccount == "") {
        alert("开户账号不能为空!");
        $("#ApplyAccount").focus();
        return;
    }
    instance[0].OrderId = instance[0].OrderID;
    //debugger
    //------------
    var strValue = [];
    $("#tbInvoice tbody tr").first().nextAll().each(function () {
        var vcIId = $("#CrmInvoiceApplyProductId", this).val();
        var orderproductid = $("#OrderProductId", this).val();
        var idInvoiceCodeId = $("#InvoiceCodeId", this).val();
        var money = $("#InvoiceMoney", this).val();
        if ($("#OrderProductId", this).val() != "") {
            if (vcIId == "") {
                vcIId = "00000000-0000-0000-0000-000000000000";
            }
            /*if (money == "") {
            alert("发票金额不能为空!");
            return;
            }*/
            strValue.push(vcIId + "︾" + orderproductid + "︾" + idInvoiceCodeId + "︾" + money);
        }
    });
    //var InvoiceApplyId = getPar1("id");
    var ExpressCompany = $("#ExpressCompany").val();
    var ExpressNumber = $("#ExpressNumber").val();
    if (flag == 1 || flag == 3) {
        if (ExpressCompany == "" || ExpressCompany == "00000000-0000-0000-0000-000000000000") {
            alert("快递公司不能为空!");
            return;
        }
        if (ExpressNumber == "") {
            alert("快递单号不能为空!");
            return;
        }
    }
    var Remark = "";
    var vApplyproductList = "";
    for (var i = 0; i < strValue.length; i++) {
        vApplyproductList += "@" + strValue[i] + "︾" + InvoiceApplyId + "︾" + ExpressCompany + "︾" + ExpressNumber + "︾" + Remark + "︾";
    }
    instance[0].ApplyProductList = vApplyproductList;

    instance[0].WorkFlowId = WorkFlowId;
    instance[0].WorkTaskId = WorkTaskId;
    instance[0].WorkFlowInsId = WorkflowInsId;
    instance[0].WorkTaskInsId = WorkTaskInsId;

    //------------
    //debugger
    var tempMoney = 0;
    if (vApplyproductList != "") {
        var listProduct = [];
        listProduct = vApplyproductList.split('@');
        for (var i = 1; i < listProduct.length; i++) {
            var money = listProduct[i].split('︾')[3];
            if (money == "") {
                alert("第" + i + "行发票金额不能为空!");
                return;
            } else {
                tempMoney += parseFloat(money.toString());
            }
        }
        if (tempMoney > $("#BillingMoney").val()) {
            alert("发票总金额不能大于开票金额!");
            return;
        }
    } else {
        if (flag != 0) {
            alert("开发票产品不能为空!");
            return;
        }
    }
    if (confirm("是否确定保存?")) {
        $("#jsonDataContent").val($.toJSON(instance[0]));
        trySave();
    }
}
var trySave = function () {
    if (flag == 1 || flag == 3) {
        action = "insert";
    }
    var SaveUrl = "AjaxData/CustomOperating.aspx?r=" + Math.random() + "&flag=1&type=" + flag + "&entity=" + entity + "&action=" + action + "&json=";
    var formObject = document.getElementById('form2');
    YAHOO.util.Connect.setForm(formObject);
    var cObj = YAHOO.util.Connect.asyncRequest('POST', SaveUrl, callback);
}
var responseSuccess = function (res) {
    try {
        //debugger
        var str = res.responseText;
        if (str == "1") {
            alert("数据保存成功");
            if (flag != 3) {
                parent.window.location.href = "../../Crm/BasePages/tooltip.aspx?worktaskInstanceId=" + WorkflowInsId;
            } else {
                //关闭当前页面
                parent.parent.CloseCurPage();
            }
        } else {
            alert(str);
            return;
        }
    } catch (e) {
    }
    finally {
    }
};
var callback = {
    success: responseSuccess,
    failure: responseFailure
};


//增加行
function AddTrRow() {
    var tr = $("#tbInvoice tr").eq(1).clone();
    tr.show();
    tr.appendTo("#tbInvoice").removeClass("selectedTr");
    iCount++;
}

//删除行
function DelTrRow() {
    //遍历tr
    $("#tbInvoice tbody tr").first().nextAll().each(function () {
        if ($(this).hasClass("selectedTr")) {
            var CrmInvoiceApplyProductId = $("#CrmInvoiceApplyProductId", this).val();
            var number = $("#InvoiceNumber", this).val();
            for (var i = 0; i < iConditionNumber.length; i++) {
                if (iConditionNumber[i] == number) {
                    iConditionNumber.splice($.inArray(number, iConditionNumber), 1);
                }
            }
            if (CrmInvoiceApplyProductId == "") {
                $(this).remove();
                iCount--;
            } else {
                DeleteData(CrmInvoiceApplyProductId);
            }
        }
    });
};

//选中行
$("#tbInvoice tr").live("click", function () {
    if ($(this).hasClass("selectedTr")) {
        $(this).removeClass("selectedTr");
    } else {
        $(this).addClass("selectedTr");
    }
});

var DeleteData = function (id) {
    var vCId = "ID='" + id + "'";
    YAHOO.util.Connect.asyncRequest('GET', "AjaxData/CustomOperating.aspx?r=" + Math.random() + "&action=delete&entity=CrmInvoiceApplyProduct&condition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                if (str == "1") {
                    $("#tbInvoice tbody tr").first().nextAll().each(function () {
                        if ($(this).hasClass("selectedTr")) {
                            var CrmInvoiceApplyProductId = $("#CrmInvoiceApplyProductId", this).val();
                            if (CrmInvoiceApplyProductId == id) {
                                $(this).remove();
                            }
                        }
                    });
                } else {
                    alert("数据删除失败!");
                    return;
                }
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}